import sys
import time
import argparse

from parse_site_ID import process_booking_data
from auth_login import AuthLogin
from booking import BookingSystem

###=============全局变量==============###
username='240854042026'
password='xyg5737152'

token='61f07664-91ee-4666-927f-528b18117793'

badminton_site=1       #抢几号羽毛球场地
time_period="晚"       #早中晚抢哪一个

Start_time=18          #几点开始抢



def print_colored(text, color="white"):
    """
    彩色打印函数
    """
    colors = {
        "red": "\033[31m",
        "green": "\033[32m",
        "yellow": "\033[33m",
        "blue": "\033[34m",
        "magenta": "\033[35m",
        "cyan": "\033[36m",
        "white": "\033[37m",
        "reset": "\033[0m"
    }
    
    color_code = colors.get(color, colors["white"])
    print(f"{color_code}{text}\033[0m")

def show_progress(current, total, prefix='', suffix='', length=30, fill='█'):
    """
    显示进度条
    """
    percent = f"{100 * (current / float(total)):.1f}"
    filled_length = int(length * current // total)
    bar = fill * filled_length + '-' * (length - filled_length)
    
    print(f'\r{prefix} |{bar}| {percent}% {suffix}', end='\r')
    if current == total:
        print()

def show_welcome():
    """
    显示欢迎界面
    """
    print_colored("=" * 50, "cyan")
    print_colored("    羽毛球场地预订系统", "cyan")
    print_colored("=" * 50, "cyan")
    print_colored("开发者: 谢峻东", "yellow")
    print()

def authserver_login():
    """
    登录测试功能
    """
    print_colored("\n[登录测试]", "green")
    
    login_url = "https://authserver.swun.edu.cn/authserver/login"

    login_data = {
        'username': username,
        'password': password
    }
    # 直接尝试登录，不检查现有登录状态
    print_colored("开始登录流程", "yellow")
    auth_login = AuthLogin(login_url)
    auth = auth_login.get_login_page(url=login_url, login_data=login_data)

    return auth
def access_booking_page(session):
    """
    访问预订页面
    """
    print_colored("\n[访问预订页面]", "green")
    
    booking = BookingSystem(session)
    
    print("正在访问羽毛球预订网站...")
    result = booking.access_booking_page()
    
    if result:
        print_colored("成功访问羽毛球预订页面!", "green")
    else:
        print_colored("访问羽毛球预订页面失败!", "red")
        # 检查是否因为未登录导致访问失败
        print_colored("请检查是否已正确登录，或登录会话已过期", "yellow")
    return booking if result else None

def parse_booking_info(session,site_num,time_num,token):
    """
    解析预订信息
    """
    print_colored("\n[解析预订信息]", "green")
    booking = BookingSystem(session)
    result = booking.get_fields_data(token)                             #####################token还没传入########################
    site_result=process_booking_data(result,site_num,time_period=time_num)  #返回你选择的场地id

    print("\n=== 您的选择 ===")
    print(f"场地: {site_result['venue_name']}")
    print("时间段:")
    for i, time_slot in enumerate(site_result['time_slots']):
        print(f"  {time_slot}")
        print(f"    ID: {site_result['ids'][i]}")
        print(f"    Opening Period ID: {site_result['openingPeriodIds'][i]}")
        print(f"    Place ID: {site_result['placeIds'][i]}")


    return site_result


def auto_book_at_time(session, site_result, token, start_time=18):
    """
    在指定时间自动预订场地
    :param session: 会话对象
    :param site_result: 场地信息
    :param token: 认证令牌
    :param start_time: 开始预订的时间（小时），默认为18点
    """
    # 等待指定时间，并每秒尝试两次，直到成功为止
    while True:
        current_time = time.localtime()
        # 精确到分的时间判断
        current_total_minutes = current_time.tm_hour * 60 + current_time.tm_min
        target_total_minutes = start_time * 60
        if current_total_minutes >= target_total_minutes:
            # 每秒尝试两次预订，直到成功
            success = False
            while not success:
                # 尝试预订
                success = select_and_book(session, site_result, token)
                if not success:
                    # 每秒两次，即每次等待0.5秒
                    time.sleep(0.5)
            # 预订成功后跳出循环
            break
        else:
            # 还未到指定时间，等待1秒后继续检查
            print("时间未到")
            time.sleep(0.5)


def select_and_book(session, site_result,token):
    """
    选择场地和时间并预订
    """
    # 确认是否提交预订
    # confirm = input("\n是否提交预订? (y/n): ")
    print_colored("\n[预定场地]", "green")
    submit = BookingSystem(session)
    result = submit.submit_booking(site_result, token=token)
    response_json = result.json()

    if response_json.get('orderId'):
        print_colored("预订成功!", "green")
        return True
    else:
        print_colored("预订失败!", "red")
        return False

def show_menu():
    """
    显示功能菜单
    """
    print_colored("\n请选择功能:", "yellow")
    print("1. 访问预订页面")
    print("2. 解析预订信息")
    print("3. 选择场地和时间")
    print("4. 提交预订")
    print("5. 完整预订流程")
    print("6. 退出程序")

def main():
    """
    主函数
    """
    show_welcome()
    try:
        # 登录
        session = authserver_login()
        if not session:
            return
            
        booking = None
        site_result=None
        while True:
            show_menu()
            choice = input("\n请输入选项编号 (1-6): ").strip()
            
            if choice == "1":
                booking = access_booking_page(session)
            elif choice == "2":
                if booking:
                    site_result=parse_booking_info(booking,site_num=badminton_site,time_num=time_period,token=token)
                else:
                    print_colored("请先访问预订页面!", "red")
            elif choice == "3":
                if site_result:
                    auto_book_at_time(session, site_result, token, start_time=Start_time)
                else:
                    print_colored("请先访问预订页面!", "red")
            elif choice == "4":
                # 完整流程：访问页面 -> 解析信息 -> 定时预订
                print_colored("\n[完整预订流程]", "green")
                booking = access_booking_page(session)
                if booking:
                    site_result = parse_booking_info(booking, site_num=badminton_site, time_num=time_period, token=token)
                    if site_result:
                        auto_book_at_time(session, site_result, token)
                    else:
                        print_colored("解析预订信息失败!", "red")
                else:
                    print_colored("访问预订页面失败!", "red")
            elif choice == "5":
                print_colored("感谢使用羽毛球场地预订系统，再见!", "cyan")
                break
            else:
                print_colored("无效选项，请重新输入!", "red")
                
    except KeyboardInterrupt:
        print_colored("\n\n程序被用户中断", "red")
        print_colored("感谢使用羽毛球场地预订系统，再见!", "cyan")
    except Exception as e:
        print_colored(f"发生错误: {e}", "red")

if __name__ == "__main__":
    main()